package com.start.common.tools;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;



public class UserAgentTools {
    public static String getDeviceInfoToString(String userAgent) {
        if (StringUtils.isBlank(userAgent)) {
            throw new RuntimeException("userAgent cant is null ");
        }
        if (!userAgent.contains("(")) {
            return null;
        }
        if (!userAgent.contains(")")) {
            return null;
        }
        return userAgent.substring(userAgent.indexOf("(") + 1, userAgent.indexOf(")"));
    }

    public static String getUserAgent(HttpServletRequest request) {
        String agent = request.getHeader("User-Agent");
        if (StringUtils.isBlank(agent)) {
            agent = request.getHeader("user-agent");
        }
        return agent;
    }

    public static String getDeviceInfoToString(HttpServletRequest request) {
        return getDeviceInfoToString(getUserAgent(request));
    }

    private final static String[] mobleAgents = {"android", "iphone", "ipod", "ipad", "windows phone", "mqqbrowser"};

    /**
     * 判断请求是否是移动端
     *
     * @param request
     * @return
     */
    public static boolean isMobileDevice(HttpServletRequest request) {
        String userAgent = getUserAgent(request).toLowerCase();
        for (String agent : mobleAgents) {
            if (userAgent.contains(agent)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断请求是否是pc客户端端
     *
     * @param request
     * @return
     */
    public static boolean isPCDevice(HttpServletRequest request) {
        return !isMobileDevice(request);
    }
}
